package mall

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"mall-go-gin/global"
	"mall-go-gin/model/common/response"
	"mall-go-gin/model/mall/request"
	"mall-go-gin/utils"
)

type MallShopCartApi struct{}

func (m *MallShopCartApi) CartItemList(c *gin.Context) {
	fmt.Println("============ CartItemList ==========")
	token := c.GetHeader("token")
	global.GVA_LOG.Info("===========token", zap.String("token", token))
	if err, shopCartItem := mallShopCartService.GetMyShoppingCartItems(token); err != nil {
		global.GVA_LOG.Error("获取购物车失败", zap.Error(err))
		response.FailWithMessage("获取购物车失败:"+err.Error(), c)
	} else {
		response.OkWithData(shopCartItem, c)
	}
}

// 添加购物车
func (m *MallShopCartApi) SaveMallShoppingCartItem(c *gin.Context) {
	token := c.GetHeader("token")
	var req request.SaveCartItemParam
	err := c.ShouldBindJSON(&req)
	if err != nil {
		global.GVA_LOG.Error("ShouldBindJSON err:", zap.Error(err))
		return
	}
	if err = mallShopCartService.SaveMallCartItem(token, req); err != nil {
		global.GVA_LOG.Error("添加购物车失败", zap.Error(err))
		response.FailWithMessage("添加购物车失败", c)
		return
	}
	response.OkWithMessage("添加购物车成功", c)
}

func (m *MallShopCartApi) UpdateMallShoppingCartItem(c *gin.Context) {
	token := c.GetHeader("token")
	var req request.UpdateCartItemParam
	_ = c.ShouldBindJSON(&req)
	err := mallShopCartService.UpdateMallCartItem(token, req)
	if err != nil {
		global.GVA_LOG.Error("修改购物车失败", zap.Error(err))
		response.FailWithMessage("修改购物车失败："+err.Error(), c)
		return
	}
	response.OkWithMessage("修改购物车成功", c)
}

func (m *MallShopCartApi) ToSettle(c *gin.Context) {
	cartItemIdsStr := c.Query("cartItemIds")
	token := c.GetHeader("token")
	cartITemIds := utils.StrToInt(cartItemIdsStr)
	if err, cartItemRes := mallShopCartService.GetCartItemsForSettle(token, cartITemIds); err != nil {
		global.GVA_LOG.Error("获取购物明细异常：", zap.Error(err))
		response.FailWithMessage("获取购物明细异常:"+err.Error(), c)
	} else {
		response.OkWithData(cartItemRes, c)
	}
}
